const db = require('../db.config')
const Sequelize = db.sequelize
const Op = Sequelize.Op

const User = Sequelize.import('../schema/user.js')
User.sync({force: false})

class userModule {
  /**
   * 用户注册
   * 
   * @param data
   */
  static async register(data) {
    return await User.create({
      name: data.name,
      password: data.password,
      email: data.email,
      roles: data.roles,
      createAt: new Date
    })
  }

  /**
   * 通过账号查询用户
   * 
   * @param name
   */
  static async getUserByName(name) {
    let value = await User.findAll({
      raw: true,
      where: {
        name: name,
        roles: 'user'
      }
    })
    return value
  }

  /**
   * 通过账号查询管理员
   * 
   * @param name
   */
  static async getAdminByName(name) {
    let sql = {
      name: name,
      roles: {
        [Op.not]: ['user']
      }
    }
    let value = await User.findAll({
      where: sql
    })
    return value
  }

  /**
   * 通过邮箱查找用户
   * 
   * @param email
   */
  static async getUserByEmail(email) {
    let value = await User.findAll({
      where: {
        email: email
      }
    })
    return value
  }

  /**
   * 通过角色查找用户
   * 
   * @param roles
   */
  static async getUserByRoles(roles) {
    let value = await User.findAll({
      where: {
        roles,
      }
    })
    return value
  }

  /**
   * 多条件查找用户
   * 
   * @param {object} { where, limit, offset }
   */
  static async getUserList({ where, total, pagination}) {
    let value = await User.findAll({
      where,
      raw: true,
      limit: +total,
      offset: total * (pagination - 1)
    })
    return value
  }

  /**
   * 多条件查找所有用户
   * 
   */
  static async getAllUserList({ where }) {
    let value = await User.findAll({
      where,
      raw: true
    })
    return value
  }
  
  /**
   * 上传头像
   * 
   * @param name - 用户账号
   * 
   * @param url - 用户头像url
   */
  static async uploadAvatarURL(name, url) {
    let user = await User.findOne({
      where: {
        name: name
      }
    })
    user.avatarURL = url;
    await user.save();
    return user
  }

  /**
   * 更新信息
   * 
   * @param name
   * @param password
   * @param email
   */
  static async updateUserInfo(name, password, email) {
    let user = await User.findOne({
      where: {
        name: name
      }
    })
    if (password) {
      user.password = password
    }
    if (email) {
      user.email = email
    }
    await user.save()
    return user
  }
}

module.exports = userModule
